package com.leantech.android.browser.ui.browser.viewmodel

import android.graphics.Bitmap
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.cscj.android.repository.repo.favorites.FavoritesRepository
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.launch
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject

class FavoriteStateViewModel : ViewModel(), KoinComponent {

    private val favoritesRepository by inject<FavoritesRepository>()

    private val currentUrlFlow = MutableStateFlow<String?>(null)

    val favoriteState = currentUrlFlow.flatMapLatest { url ->
        if (url.isNullOrBlank()) {
            flowOf(false)
        } else {
            favoritesRepository.checkUrlFavorite(url)
        }
    }

    fun updateCurrentUrl(url: String) {
        viewModelScope.launch {
            currentUrlFlow.emit(url)
        }
    }

    fun unFavorite() {
        viewModelScope.launch {
            currentUrlFlow.value?.also { url ->
                favoritesRepository.deleteByUrl(url)
            }
        }
    }

    fun favorite(title:String, favicon:Bitmap?){
        viewModelScope.launch {
            currentUrlFlow.value?.also { url ->
                favoritesRepository.favoriteLink(title, url, favicon)
            }
        }
    }


}